﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
using testServer.XcoAppSpaces.Core;
using XcoAppSpaces.Contracts.Logging;
using XcoAppSpaces.Core;
using XcoAppSpaces.Core.Ports;
using TypeResolve;

namespace TestApp.Client
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
		private int count = 1;
		private IXcoAppSpace space;
		private PCompactWorker worker;
		private Port<string> responsePort;
		private ObservableCollection<string> evtList = new ObservableCollection<string>();
	    private TaskScheduler uiTaskScheduler;

        public MainPage()
        {
            this.InitializeComponent();
	        XcoLoggerFactory.CreateInstance = _ => new DebugLogger();
	        //TypeUtils.CurrentAssemblies = TypeUtils.LoadCurrentAssemblies();
			space = new XcoAppSpace("tcp.port=0;tcp.key=testPass123");
	        lvEvents.ItemsSource = evtList;
	        uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
        }

		private void btTest_Click(object sender, RoutedEventArgs e)
		{
			Task.Run(() =>
			{
				InitWorkerAndResponsePort();
				var msg = new CompactRequest {Msg = "Request " + count++, ResponsePort = responsePort};
				worker.Post(msg);
				Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => evtList.Add("Sent: " + msg.Msg));
			});
		}

		private void InitWorkerAndResponsePort()
		{
			if (worker == null)
			{
				worker = space.ConnectWorker<PCompactWorker>("localhost:8000/myworker");
				responsePort = new Port<string>(
					r => evtList.Add("Response received: " + r),
					new PortReceiverOptions { TaskScheduler = uiTaskScheduler });
			}
		}
    }
}
